import React, { useState, forwardRef, useCallback, useEffect, useRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Flex, Input, Tag, App, Tooltip, theme } from 'antd';
import styles from './index.module.scss';

/**
 * WhereSellEditor
 * value: [url, url]
 * onChange: (nextList) => void
 */
export default forwardRef(({ value = [], onChange }, ref) => {
  const initState = () => ({
    inputVisible: false,
    inputValue: '',
  });
  const [state, setState] = useState(initState);
  const { message } = App.useApp();
  const { token } = theme.useToken();

  const list = Array.isArray(value)
    ? value.filter(Boolean)
    : (typeof value === 'string' ? value.split(',').map(i => i.trim()).filter(Boolean) : []);
  
  const inputRef = useRef(null);

  useEffect(() => {
    if (state.inputVisible) inputRef.current?.focus();
  }, [state.inputVisible]);

  // 从URL中获取域名
  const getDomain = useCallback((raw='') => {
    if (!raw || typeof raw !== 'string') return '';
    const s = raw.trim();
    const match = s.match(/^(?:https?:\/\/)?([^\/?#:]+)(?:[\/?#:]|$)/i);
    return match ? match[1] : '';
  }, []);

  const normalizeUrl = useCallback((raw='') => {
    if (!raw) return '';
    const trimmed = raw.trim();
    // 如果没有协议，默认加 https://
    if (!/^https?:\/\//i.test(trimmed)) {
      return `https://${trimmed}`;
    }
    return trimmed;
  }, []);

  // 判断是否为有效的链接地址（宽松判断）
  const isUrl = useCallback((str='') => {
    if (typeof str !== 'string') return false;
    const trimmed = str.trim();
    if (!trimmed) return false;

    let urlToTest = trimmed;
    if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) urlToTest = 'http://' + trimmed;

    try {
      const url = new URL(urlToTest);
      if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
      const host = url.hostname;
      if (!host) return false;

      // 👇 关键改进：要求 hostname 至少包含一个点（排除 'aaaa', 'localhost' 等）
      if (!host.includes('.')) return false;

      return true;
    } catch {
      return false;
    }
  }, []);

  const updateValue = (next=[]) => {
    onChange?.(next);
  };

  const showInput = () => setState(o => ({ ...o, inputVisible: true }));
  const hideInput = () => setState(initState);

  const handleInputChange = e => setState(o => ({ ...o, inputValue: e.target.value }));

  const handleInputConfirm = () => {
    message.destroy();
    const raw = (state.inputValue || '').trim();
    if (!raw) return hideInput();
    // 保存原始文本（不强制添加协议）
    const valueToSave = raw;
    if (list.includes(valueToSave)) {
      message.info('该地址已存在');
      return hideInput();
    }
    updateValue([...list, valueToSave]);
    hideInput();
  };

  const handleRemove = removed => {
    const next = list.filter(i => i !== removed);
    updateValue(next);
  };

  const tagInputStyle = {
    width: 64,
    height: 22,
    marginInlineEnd: 8,
    verticalAlign: 'top',
  };
  const tagPlusStyle = {
    height: 22,
    background: token.colorBgContainer,
    borderStyle: 'dashed',
  };

  return (
    <div className={styles['container']}>
      <Flex gap="4px 0" wrap>
        {list.map(item => {
          const linkable = isUrl(item);
          const href = linkable ? normalizeUrl(item) : '';
          const domain = linkable ? getDomain(href) : '';
          const displayText = linkable ? (domain || href) : (item || '');
          const isLong = displayText.length > 20;
          const tagElem = (
            <Tag key={item} closable onClose={() => handleRemove(item)} style={{ userSelect: 'none' }}>
              {linkable ? (
                <a href={href} target="_blank" rel="noreferrer">{isLong ? `${displayText.slice(0, 20)}...` : displayText}</a>
              ) : (
                <span>{isLong ? `${displayText.slice(0, 20)}...` : displayText}</span>
              )}
            </Tag>
          );
          return isLong ? (
            <Tooltip title={displayText} key={item}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
        {state.inputVisible ? (
          <Input
            ref={inputRef}
            type="text"
            size="small"
            style={tagInputStyle}
            value={state.inputValue}
            placeholder="输入网址后回车添加"
            onChange={handleInputChange}
            onBlur={handleInputConfirm}
            onPressEnter={handleInputConfirm}
          />
        ) : (
          <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
            添加购买地址
          </Tag>
        )}
      </Flex>
    </div>
  );
});